<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>22_RegExp-正则练习-时间格式化</title>
</head>
<body>

  <h2 class="time"></h2>
  
  <script>
    
    function formatTime(timestamp, fmtString) {
      // 1.将时间戳转成Date
      const data = new Date(timestamp);
      // 2.获取到值
      // const year = date.getFullYear()
      // const month = date.getMonth() + 1
      // const day = date.getDate()
      // const hour = date.getHours()
      // const minute = date.getMinutes()
      // const second = date.getSeconds()

      // // 3.创建正则
      // const yearRe = /y+/
      // const monthRe = /M+/

      // 组装匹配值
      const dateObj = {
        "y+": data.getFullYear(),
        "M+": data.getMonth() + 1,
        "d+": data.getDate(),
        "h+": data.getHours(),
        "m+": data.getMinutes(),
        "s+": data.getSeconds()
      }

      // 4.将正则匹配到的值替换成对应的值
      for (const key in dateObj) {
        const keyRe = new RegExp(key)
        console.log(keyRe, fmtString);
        if (keyRe.test(fmtString)) {
          const value = (dateObj[key] + "").padStart(2, "0")
          fmtString = fmtString.replace(keyRe, value)
        }
      }
      return fmtString
    }

    const productJSON = {
      name: "iPhone",
      newPrice: 4999,
      oldPrice: 5999,
      endTime: 1659252301637
    }
    const timer = formatTime(productJSON.endTime, "yyyy*MM*dd hh:mm:ss")
    console.log(timer);
    


  </script>
  
</body>
</html>